<?php

namespace App\Kuafu\Export\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Shop\Model\SourceMaterialTemplateModel;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Model\User;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Kuafu\File\FileUtil;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\GeneralFs\CardStyle\FsCardGrid;
use Kuafu\GeneralFs\FsCardEstablish;

class ExportDownloadModel extends BaseModel
{
    use KfUid, KfSoftDeletes;

    protected $connection = 'mysql';
    protected $table      = 'export_downloads';
    protected $primaryKey = 'id';
    protected $fillable   = [
        'name',
        'ext',
        'path',
        'startTime',
        'completeTime',
        'expireTime',
        'status',
        'client',
        'fileType',
        'fileTypeText',
        'params',
        'isDeleted',
        'createdByUid',
        'updatedByUid',
    ];

    const STATUS_INIT   = 0; // 初始化，还未进队列
    const STATUS_ING    = 1;
    const STATUS_FINISH = 2;
    const STATUS_ERROR  = 3;
    const STATUS_TEXT   = [
        self::STATUS_INIT   => '排队中',
        self::STATUS_ING    => '导出中',
        self::STATUS_FINISH => '导出完成',
        self::STATUS_ERROR  => '导出异常',
    ];

    // 端
    const CLIENT_TYPE_WEB = 1; // web
    const CLIENT_TYPE_APP = 2; // app

    const FILE_TYPE_WEB_IN_ORDER = 1; // web-堂食订单明细

    const FILE_TYPE_APP_IN_GOODS = 100; // app-堂食菜品销售
    const FILE_TYPE_APP_WM_GOODS = 101; // app-外卖菜品销售
    const FILE_TYPE_APP_IN_ORDER = 102; // app-堂食订单明细
    const FILE_TYPE_APP_WM_ORDER = 103; // app-外卖订单明细
    const FILE_TYPE_APP_PAY      = 104; // app-支付明细统计

    const FILE_TYPE_APP_SOURCE_MATERIAL_TEMPLATE = 200; // app-物料素材模版下载
    const FILE_TYPE_APP_DISTRIBUTION_QRCODE      = 201; // app-渠道二维码下载
    const FILE_TYPE_APP_MYBANK_WALLET_RECORD     = 202; // app-网商钱包记录下载
    const FILE_TYPE_WEB_ACTIVITY_MATERIAL        = 203; // web-rms-活动管理-私域活动物料素材批量生成
    const FILE_TYPE_WEB_GIFT_ACTIVITY_MATERIAL   = 204; // web-rms-活动管理-满赠私域活动物料素材批量生成

    const FILE_TYPE_WEB_MYBANK_RECORD            = 300; // web-rms-数据中心-网商商户管理-商户收支记录

    const FILE_TYPE_WEB_TIGER_WORK_ORDER              = 400; // web-tiger-工单导出
    const FILE_TYPE_WEB_TIGER_APPRAISE                = 401; // web-tiger-评价反馈导出
    const FILE_TYPE_WEB_ALBUM_RESOURCE                = 402; // web-tiger-运营app-相册资源批量下载
    const FILE_TYPE_WEB_ARTICLE_HOLISTIC_ANALYSIS     = 403; // web-tiger-内容管理 - 文章整体分析
    const FILE_TYPE_WEB_ARTICLE_SINGLE_ANALYSIS       = 404; // web-tiger-内容管理 - 单篇文章分析
    const FILE_TYPE_WEB_CATEGORY_HOLISTIC_ANALYSIS    = 405; // web-tiger-专题管理 - 整体分析
    const FILE_TYPE_WEB_CATEGORY_SINGLE_ANALYSIS      = 406; // web-tiger-专题管理 - 单独分析
    const FILE_TYPE_WEB_SHOP_ORDER_ACTIVITY_SHOP_LIST = 407; // web-tiger-门店订货活动 - 门店列表
    const FILE_TYPE_WEB_SHOP_ACTIVITY_SHOP_LIST       = 408; // web-tiger-门店活动 - 门店数据列表
    const FILE_TYPE_WEB_SHOP_ACTIVITY_LIST            = 409; // web-tiger-门店活动 - 数据列表

    const TYPE_SHOP_LICENSE_RECORDS_LIST              = 410; // web-tiger-门店证件备案列表

    const FILE_TYPE_WEB_SHOP_RECORD_LIST       = 500;//web-rms-门店备案-门店列表
    const FILE_TYPE_WEB_SHOP_STAFF_RECORD_LIST = 501;//web-rms-门店备案-员工备案列表
    const FILE_TYPE_APP_SHOP_PRICE_TAG_LIST    = 510; // app 价签列表

    // tiger 1000+code
    const FILE_TYPE_TIGER_MIN = 1000;


    const FILE_TYPE_TEXT = [
        self::FILE_TYPE_WEB_IN_ORDER                      => '堂食订单明细',
        self::FILE_TYPE_APP_IN_GOODS                      => '堂食菜品销售',
        self::FILE_TYPE_APP_WM_GOODS                      => '外卖菜品销售',
        self::FILE_TYPE_APP_IN_ORDER                      => '堂食订单明细',
        self::FILE_TYPE_APP_WM_ORDER                      => '外卖订单明细',
        self::FILE_TYPE_APP_PAY                           => '支付明细统计',
        self::FILE_TYPE_APP_SOURCE_MATERIAL_TEMPLATE      => '物料素材模版下载',
        self::FILE_TYPE_APP_MYBANK_WALLET_RECORD          => '网商钱包明细',
        self::FILE_TYPE_WEB_TIGER_WORK_ORDER              => '工单导出明细',
        self::FILE_TYPE_WEB_TIGER_APPRAISE                => '评价反馈导出明细',
        self::FILE_TYPE_WEB_ALBUM_RESOURCE                => '运营app相册资源批量下载',
        self::FILE_TYPE_APP_DISTRIBUTION_QRCODE           => '渠道二维码下载',
        self::FILE_TYPE_WEB_ACTIVITY_MATERIAL             => '满10元开业活动物料（必做）',
        self::FILE_TYPE_WEB_ARTICLE_HOLISTIC_ANALYSIS     => '文章整体分析下载',
        self::FILE_TYPE_WEB_ARTICLE_SINGLE_ANALYSIS       => '单篇文章分析下载',
        self::FILE_TYPE_WEB_CATEGORY_HOLISTIC_ANALYSIS    => '专题整体分析下载',
        self::FILE_TYPE_WEB_CATEGORY_SINGLE_ANALYSIS      => '专题单篇分析下载',
        self::FILE_TYPE_WEB_GIFT_ACTIVITY_MATERIAL        => '日常活动物料（必做）',
        self::FILE_TYPE_WEB_MYBANK_RECORD                 => '网商商户收支记录',
        self::FILE_TYPE_WEB_SHOP_ORDER_ACTIVITY_SHOP_LIST => '门店订货活动 - 门店列表',
        self::FILE_TYPE_WEB_SHOP_ACTIVITY_SHOP_LIST       => '门店活动 - 门店列表',
        self::FILE_TYPE_WEB_SHOP_ACTIVITY_LIST            => '门店活动 - 列表',
        self::FILE_TYPE_WEB_SHOP_RECORD_LIST              => '门店备案门店列表',
        self::FILE_TYPE_WEB_SHOP_STAFF_RECORD_LIST        => '门店备案员工列表',
        self::TYPE_SHOP_LICENSE_RECORDS_LIST              => '门店证件备案下载',
        self::FILE_TYPE_APP_SHOP_PRICE_TAG_LIST           => '价签导出文件下载',
    ];

    const FILE_TYPE_EXT = [
        self::FILE_TYPE_WEB_IN_ORDER                      => 'xlsx',
        self::FILE_TYPE_APP_IN_GOODS                      => 'xlsx',
        self::FILE_TYPE_APP_WM_GOODS                      => 'xlsx',
        self::FILE_TYPE_APP_IN_ORDER                      => 'xlsx',
        self::FILE_TYPE_APP_WM_ORDER                      => 'xlsx',
        self::FILE_TYPE_APP_PAY                           => 'xlsx',
        self::FILE_TYPE_APP_MYBANK_WALLET_RECORD          => 'xlsx',
        self::FILE_TYPE_APP_SOURCE_MATERIAL_TEMPLATE      => 'png',
        self::FILE_TYPE_WEB_TIGER_WORK_ORDER              => 'csv',
        self::FILE_TYPE_WEB_TIGER_APPRAISE                => 'csv',
        self::FILE_TYPE_WEB_ALBUM_RESOURCE                => '7z',
        self::FILE_TYPE_APP_DISTRIBUTION_QRCODE           => 'png',
        self::FILE_TYPE_WEB_ACTIVITY_MATERIAL             => '7z',
        self::FILE_TYPE_WEB_GIFT_ACTIVITY_MATERIAL        => '7z',
        self::FILE_TYPE_WEB_ARTICLE_HOLISTIC_ANALYSIS     => 'csv',
        self::FILE_TYPE_WEB_ARTICLE_SINGLE_ANALYSIS       => 'csv',
        self::FILE_TYPE_WEB_CATEGORY_HOLISTIC_ANALYSIS    => 'csv',
        self::FILE_TYPE_WEB_CATEGORY_SINGLE_ANALYSIS      => 'csv',
        self::FILE_TYPE_WEB_MYBANK_RECORD                 => 'xlsx',
        self::FILE_TYPE_WEB_SHOP_ORDER_ACTIVITY_SHOP_LIST => 'csv',
        self::FILE_TYPE_WEB_SHOP_ACTIVITY_SHOP_LIST       => 'csv',
        self::FILE_TYPE_WEB_SHOP_ACTIVITY_LIST            => 'csv',
        self::FILE_TYPE_WEB_SHOP_RECORD_LIST              => 'xlsx',
        self::FILE_TYPE_WEB_SHOP_STAFF_RECORD_LIST        => 'xlsx',
        self::TYPE_SHOP_LICENSE_RECORDS_LIST              => 'xlsx',
        self::FILE_TYPE_APP_SHOP_PRICE_TAG_LIST           => 'pdf',
    ];

    // 通用过期时间
    const EXPIRE_SECONDS = 30 * 86400;

    // tmp过期时间
    const EXPIRE_SECONDS_TMP = 3 * 86400;

    public function userRel(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'createdByUid');
    }

    public function getFileTypeTextDefineAttribute(): string
    {
        return $this->fileTypeText ?: (self::FILE_TYPE_TEXT[$this->fileType] ?? '');
    }

    public function add(int $client, int $fileType, array $params, string $name = '', int $createdByUid = 0)
    {
        $shopId       = $params['shopId'] ?? 0;
        $shopCode     = $params['shopCode'] ?? '';
        $startAt      = $params['showStartAt'] ?? '';
        $endAt        = $params['showEndAt'] ?? '';
        $imgType      = $params['imgType'] ?? 0;
        $templateInfo = $params['templateInfo'] ?? [];

        $time          = time();
        $expireSeconds = self::EXPIRE_SECONDS;
        if (in_array($fileType,
                [
                    self::FILE_TYPE_WEB_TIGER_WORK_ORDER,
                    self::FILE_TYPE_WEB_TIGER_APPRAISE,
                    self::FILE_TYPE_WEB_ALBUM_RESOURCE,
                    self::FILE_TYPE_WEB_ARTICLE_HOLISTIC_ANALYSIS,
                    self::FILE_TYPE_WEB_ARTICLE_SINGLE_ANALYSIS,
                    self::FILE_TYPE_WEB_CATEGORY_SINGLE_ANALYSIS,
                    self::FILE_TYPE_WEB_CATEGORY_HOLISTIC_ANALYSIS,
                    self::FILE_TYPE_WEB_SHOP_ORDER_ACTIVITY_SHOP_LIST,
                    self::FILE_TYPE_WEB_SHOP_ACTIVITY_SHOP_LIST,
                    self::FILE_TYPE_WEB_SHOP_ACTIVITY_LIST,
                    self::TYPE_SHOP_LICENSE_RECORDS_LIST,
                    self::FILE_TYPE_APP_SHOP_PRICE_TAG_LIST,
                ]) || $fileType >= self::FILE_TYPE_TIGER_MIN) {//远程调用导出 状态 导出中
            $status        = self::STATUS_ING;
            $startTime     = $time;
            $expireSeconds = self::EXPIRE_SECONDS_TMP;
        } else {
            $status    = self::STATUS_INIT;
            $startTime = 0;
        }

        // 报表名称
        if (!$name) {
            $name      = $this->buildFileName($shopId, $startAt, $endAt, $fileType, $client, $templateInfo, $imgType,
                $shopCode);
        }

        return self::query()->create([
            'name'         => $name,
            'path'         => '',
            'ext'          => self::FILE_TYPE_EXT[$fileType] ?? '',
            'completeTime' => 0,
            'expireTime'   => $time + $expireSeconds,
            'status'       => $status,
            'client'       => $client,
            'fileType'     => $fileType,
            'params'       => json_encode($params, JSON_UNESCAPED_UNICODE),
            'startTime'    => $startTime,//任务开始执行时间
            'createdByUid' => $createdByUid,//创建人id
        ]);
    }

    /**
     * 导出报表名称
     * @param int $shopId
     * @param int $startAt
     * @param int $endAt
     * @param int $fileType
     * @param int $client
     * @param array $templateInfo
     * @param int $imgType
     * @param string $shopCode
     * @return string
     */
    public function buildFileName(
        int $shopId,
        int $startAt,
        int $endAt,
        int $fileType,
        int $client,
        array $templateInfo = [],
        int $imgType = 0,
        string $shopCode = ''
    ): string {
        $startAt      = date('Y-m-d', $startAt);
        $endAt        = date('Y-m-d', $endAt);
        switch ($fileType) {
            case ExportDownloadModel::FILE_TYPE_APP_SOURCE_MATERIAL_TEMPLATE://物料素材下载
                $name = $templateInfo['name'] . '(' . $templateInfo['size'] . ')';
                if ($imgType == SourceMaterialTemplateModel::TEMPLATE_IMG_TYPE_REVERSE) {
                    $name .= SourceMaterialTemplateModel::TEMPLATE_IMG_TYPE_TEXT[$imgType];
                }
                $name .= '-' . $startAt . '-' . $endAt . '_' . date('H:i:s');
                break;
            default:
                // 命名格式：门店编号+报表类型+时间范围+下载时间
                // 1825-堂食菜品明细_2022-11-01-2022-11-18_17:13:30
                $fileTypeText = ExportDownloadModel::FILE_TYPE_TEXT[$fileType] ?? '';
                $name         = $fileTypeText . '_' . $startAt . '-' . $endAt . '_' . date('H:i:s');
                if ($shopCode) {
                    $name = $shopCode . '-' . $name;
                } elseif ($client == self::CLIENT_TYPE_APP && $shopId) {
                    $shopCode = ShopService::getShopInfo($shopId)->kfShopCode;
                    $name     = $shopCode . '-' . $name;
                }
                break;
        }
        return $name;
    }

    /**
     * 导出中
     * @return void
     */
    public function dealing(): void
    {
        $this->status    = self::STATUS_ING;
        $this->startTime = time();
        $this->save();
    }

    /**
     * 导出一场
     * @return void
     */
    public function dealError(): void
    {
        $this->status = self::STATUS_ERROR;
        $this->save();
    }

    /**
     * 导出完成
     * @param string $path
     * @return void
     */
    public function finish(string $path): void
    {
        $this->status       = self::STATUS_FINISH;
        $this->completeTime = time();
        $this->path         = $path;
        $this->save();
    }

    public function del(int $id): int
    {
        return self::query()->where('id', $id)->update(['isDeleted' => 1]);
    }

    /**
     * web端导出下载完成飞书通知
     * @param ExportDownloadModel $export
     * @param string $path
     * @throws \Exception
     */
    public static function sendFs(ExportDownloadModel $export, string $path = '')
    {
        if ($export->createdByUid && $export->client == self::CLIENT_TYPE_WEB) {
            $user = User::query()->where('id', $export->createdByUid)->first();
            if (!$path) {
                $path = $export->path;
            }
            if ($user && $path) {
                $elements = (new FsCardGrid())
                    ->pushTd('**报表名称：** ' . $export->name, false)
                    ->pushTd('**用户名称：** ' . $user->username, false)
                    ->pushTd('**开始时间：** ' . date('Y-m-d H:i:s', $export->createdAt->timestamp), false)
                    ->pushTd('**完成时间：** ' . date('Y-m-d H:i:s'), false)
                    ->getElement();

                $card = (new FsCardEstablish())
                    ->setHeader('blue', '报表下载成功')
                    ->pushElements($elements)
                    ->pushElements(['tag' => 'hr'])
                    ->setButton('点我下载', FileUtil::domain() . '/' . $path)
                    ->getTemplateArr();

                BuildFs::newRobot('center', BuildFs::MSG_TYPE_CARD, BuildFs::MODULE_TYPE_APP)
                       ->setCardContent($card)
                       ->setFeishuId($user->feishuUserId)
                       ->send();
            }
        }
    }
}
